package com.yequan.designpattern.singleton.application;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

public class SingletonProperty {

    private static Properties prop;
    private static final String fileName = "config.properties";

    private static class SingletonPropertyHolder {
        private static final SingletonProperty instance = new SingletonProperty();
    }

    private SingletonProperty() {
        try {
            prop = new Properties();
            InputStream resourceAsStream =
                    SingletonProperty.class.getClassLoader().getResourceAsStream(fileName);
            prop.load(new InputStreamReader(resourceAsStream));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SingletonProperty getInstance() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return SingletonPropertyHolder.instance;
    }

    public String getProperty(String key) {
        String value = prop.getProperty(key.trim());
        if (value == null) {
            return null;
        }
        return value.trim();
    }

    public String getProperty(String key, String defaultValue) {
        String value = prop.getProperty(key.trim());
        if (null == value) {
            value = defaultValue;
        }
        return value.trim();
    }

}
